package com.sc.nft.consume;

import cn.hutool.core.util.StrUtil;
import com.sc.nft.entity.Order;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.IncomeService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.util.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.FIRST_LEVEL_DIRECT_PUSH_INCOME+"${spring.profiles.active}",consumerGroup =  MessageTopic.FIRST_LEVEL_DIRECT_PUSH_INCOME+"${spring.profiles.active}")
@Component
@Slf4j
public class FirstLevelDirectPushIncomeConsumer implements RocketMQListener<Order> {

    @Resource
    private Redisson redisson;

    @Resource
    private IncomeService incomeService;

    @Override
    public void onMessage(Order order) {
        RLock lock = redisson.getLock(RedisKeyEnum.DIRECT_PURCHASE_LOCK.getKey() + order.getId());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                log.info("一级市场直推收益: " + order.getOrderNo() + " 开始结算");
                incomeService.firstDirectPushIncome(order);
            }else{
                throw new GlobalRunTimeException(ErrorCode.FIRSTLEVE_INCOME_CAL_ERROR);
            }
        } catch (Exception e) {
            log.error("一级收益消费异常:{}",order,e);
            WeChatUtil.sendWeChatMessage(StrUtil.format("一级收益消费异常,订单id:{},异常信息:{}",order.getId(),e));
            throw new GlobalRunTimeException(ErrorCode.FIRSTLEVE_INCOME_CAL_ERROR);
        } finally {
            lock.unlock();
        }
    }
}
